package de.homelabs.spring.freemarker.service;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.springframework.stereotype.Component;

import de.homelabs.spring.freemarker.domain.HLTemplateElement;
import freemarker.cache.TemplateLoader;

/**
 * Wrapper to use HLTemplateManager als FreemarkerTemplateLoader
 * 
 * @author D.Mueller
 *
 */
@Component("hLTemplateManagerTemplateLoader")
public class HLTemplateManagerTemplateLoader implements TemplateLoader {

	@Override
	public Object findTemplateSource(String name) throws IOException {
		return HLFreeMarkerTemplateManager.getInstance().findTemplate(name);
	}

	@Override
	public long getLastModified(Object templateSource) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Reader getReader(Object templateSource, String encoding)
			throws IOException {
		if (templateSource instanceof HLTemplateElement){
			Reader reader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(((HLTemplateElement) templateSource).getTemplateUrl()));
			return reader;
		} else
			return null;
	}

	@Override
	public void closeTemplateSource(Object templateSource) throws IOException {
		// TODO Auto-generated method stub

	}

}
